package ru.autofan.logic;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ru.autofan.domain.AuthRole;
import ru.autofan.domain.Role;
import ru.autofan.domain.User;
import ru.autofan.domain.UserPersonalInfo;
import ru.autofan.domain.UserRegistrationRequest;

public class UserService extends BasicService {

	private UserPersonalInfo createPersonalInfo(UserRegistrationRequest request) {
		UserPersonalInfo personalInfo = new UserPersonalInfo();
		personalInfo.setFirstName(request.getFirstName());
		personalInfo.setLastName(request.getLastName());
		personalInfo.setSecondName(request.getSecondName());
		return personalInfo;
	}

	private User createUserObject(UserRegistrationRequest request) {
		User user = new User();
		user.setEmail(request.getEmail());
		user.setUPassword(request.getUPassword());
		setRoleAttr(user);
		return user;
	}

	public User findUserbyCode(String code) {
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("code", code);
		return getDaoSupporter().getUniqueObject(User.class,
				"from User where code = :code");
	}

	public User findUserbyEmail(String email) {
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("email", email);
		return getDaoSupporter().getUniqueObject(User.class,
				"from User where email = :email", params);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void registerUser(String uuid) throws Exception {
		if (StringUtils.isBlank(uuid)) {
			throw new Exception("uuid required for this operation");
		}
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("uuid", uuid);
		UserRegistrationRequest request = getDaoSupporter().getUniqueObject(
				UserRegistrationRequest.class,
				"from UserRegistrationRequest where uuid=:uuid", params);
		if (request == null) {
			throw new Exception("uuid not found in database");
		}
		User user = createUserObject(request);
		user.setPersonalInfo(createPersonalInfo(request));
		getDomainFactory().save(user);
		getDomainFactory().delete(request);
	}

	private void setRoleAttr(User user) {
		Set<Role> set = new HashSet<Role>();
		set.add(getServiceLocator().getService(RoleService.class).getRole("USER", AuthRole.class));
		user.setRoles(set);
	}
	
	public boolean isUserExists(String email, String pwd) {
		if (StringUtils.isBlank(email) || StringUtils.isBlank(pwd)) {
			return false;
		}
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("email", email);
		params.put("uPassword", pwd);
		Number count = getDaoSupporter().getUniqueObject(
				Number.class,
				"select count(*) from User where email=:email and uPassword=:uPassword", params);
		return count.intValue() > 0;
	}

}
